import 'whatwg-fetch';
import * as types from './mutation-type';

/**
 * 1、get请求
 *  export const userFetch = () => {
 *      return fetch('')
 *          .then(res => res.json())
 *   }
 *
 * 2、post请求
 *  export const investInterestFetch = (options) => {
 *   return fetch('',
 *      {
 *          method: 'POST',
 *         body: JSON.stringify(options)
 *    })
 *   .then(res => res.json())
 *  }
 */

/**
 * get请求
 * @param  {String} options.url   api地址
 * @param  {String} options.query query参数
 * @return {Promise}               Promise
 */
const _get = (url) => {

    return fetch(url)
    .then((res) => {
        if (res.status >= 200 && res.status < 300) {
            return res.json();
        }
        return Promise.reject(new Error(res.status));
    });
};

/**
 * post请求
 * @param  {String} url    api地址
 * @param  {Object} params 包含post内容的object
 * @return {Promise}        Promise
 */
const _post = (url, params) => {
    return fetch(url, {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(params),
    })
  .then((res) => {
      if (res.status >= 200 && res.status < 300) {
          return res.json();
      }
      return Promise.reject(new Error(res.status));
  });
};

/**
 * 获取用户信息
 * @param  {Function} options.dispatch store对象解构出来的函数，无需手动提供
 * @return {Promise}                  Promise
 */

export const userFetch = ({ commit }) => {

    return _get('')
        .then((json) => {
            if (json) {
                commit('RECEIVE_PRODUCTS', json);
                return json;
            }
            return Promise.reject(new Error('fetchTopicLists failure'));
        })
        .catch((error) => {
            return Promise.reject(error);
        });


};
